import { asyncRoutes, constantRoutes } from '@neu/biz-core/router'

/**
 * route的meta中定义code时，认为该菜单是权限菜单。否则认为是公共菜单
 * @param hisMenus
 * @param route
 */
function hasPermission(hisMenus, route) {
  if (hisMenus === 'all') {
    return true
  }
  if (route.meta && route.meta.code) {
    return hisMenus.some(m => route.meta.code === m)
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param hisMenus
 */
export function filterAsyncRoutes(routes, hisMenus) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(hisMenus, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, hisMenus)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, hisMenus) {
    return new Promise(resolve => {
      // if (hisMenus.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, hisMenus)
      const filterDuplicateRouters = []
      accessedRoutes.forEach(it => {
        if (!filterDuplicateRouters.some(o => o.path === it.path)) {
          filterDuplicateRouters.push(it)
        }
      })
      // }
      commit('SET_ROUTES', filterDuplicateRouters)
      resolve(filterDuplicateRouters)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
